<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/index.css">
    <link href="./css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="./layui/css/layui.css">
</head>

<body>
    <div class="containner">
        <div class="header">
            <div class="supers">
                <div class="supers_left_meun" id="supers_left_meun">
                    <svg fill="#FFFFFF" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                        class="bi bi-chevron-left" viewBox="0 0 16 16">
                        <path fill-rule="evenodd"
                            d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z" />
                    </svg>
                </div>
                <div class="supers_content">
                    FREE SHIPPING AT £200
                </div>
                <div class="supers_right_meun" id="supers_right_meun">
                    <svg fill="#FFFFFF" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                        class="bi bi-chevron-right" viewBox="0 0 16 16">
                        <path fill-rule="evenodd"
                            d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z" />
                    </svg>
                </div>
            </div>
            <div class="navs">
                <div class="header_left">
                    <span class="tabBox">All</span>
                    <span class="tabBox">SHOP</span>
                    <span class="tabBox">RECIPES</span>
                    <span class="tabBox">INFO</span>
                </div>
                <div class="header_center">
                    <img src="./img/838c114d87e8b11ee26e50706af61c2.png" alt="" style="height: 115px;">
                </div>
                <div class="header_right">
                    <svg id="register" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                        class="bi bi-person-gear" viewBox="0 0 16 16">
                        <path fill-rule="evenodd"
                            d="M11 5a3 3 0 1 1-6 0 3 3 0 0 1 6 0ZM8 7a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z" />
                        <path
                            d="M8.256 14a4.474 4.474 0 0 1-.229-1.004H3c.001-.246.154-.986.832-1.664C4.484 10.68 5.711 10 8 10c.26 0 .507.009.74.025.226-.341.496-.65.804-.918C9.077 9.038 8.564 9 8 9c-5 0-6 3-6 4s1 1 1 1h5.256Z" />
                        <path fill-rule="evenodd"
                            d="M11.886 9.46c.18-.613 1.048-.613 1.229 0l.043.148a.64.64 0 0 0 .921.382l.136-.074c.561-.306 1.175.308.87.869l-.075.136a.64.64 0 0 0 .382.92l.149.045c.612.18.612 1.048 0 1.229l-.15.043a.64.64 0 0 0-.38.921l.074.136c.305.561-.309 1.175-.87.87l-.136-.075a.64.64 0 0 0-.92.382l-.045.149c-.18.612-1.048.612-1.229 0l-.043-.15a.64.64 0 0 0-.921-.38l-.136.074c-.561.305-1.175-.309-.87-.87l.075-.136a.64.64 0 0 0-.382-.92l-.148-.045c-.613-.18-.613-1.048 0-1.229l.148-.043a.64.64 0 0 0 .382-.921l-.074-.136c-.306-.561.308-1.175.869-.87l.136.075a.64.64 0 0 0 .92-.382l.045-.148ZM14 12.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z" />
                    </svg>
                    <!-- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                        class="bi bi-search" viewBox="0 0 16 16">
                        <path
                            d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z" />
                    </svg> -->
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bag"
                        viewBox="0 0 16 16">
                        <path
                            d="M8 1a2.5 2.5 0 0 1 2.5 2.5V4h-5v-.5A2.5 2.5 0 0 1 8 1zm3.5 3v-.5a3.5 3.5 0 1 0-7 0V4H1v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4h-3.5zM2 5h12v9a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V5z" />
                    </svg>
                    <span style="margin-left: 30px;cursor: pointer;" id="goEn">英文</span>

                </div>
            </div>
        </div>
        <!-- banner展示 -->
        <div class="banners">
            <img src="./img/Buy_Dragon_Fruit_FINE_WILD_UK.png" alt="" style="width: 100%;height: 100%;">
        </div>
        <!-- 商品展示 -->
        <div class="shop">
            <!-- //////// -->
        </div>
        <!-- 商品展示2 -->
        <div class="shop2" id="shop2">
            <!-- // -->
        </div>
        <!-- 页脚信息部分 -->
        <div class="footer">
            <div class="footerInfo1">
                <span class="footerNav" data-urls="./protocol.html" >PRIVACY POLICY</span>
                <span class="footerNav" data-urls="./protocol.html" >TERMS OF SERVICE</span>
                <span class="footerNav" data-urls="./protocol.html" >SHIPPING POLICY</span>
                <span class="footerNav" data-urls="./protocol.html" >RETURN POLICY</span>
            </div>
            <div class="footerInfo2">
                <span>Copyright @2024-</span>
                <span>Re_Bagel</span>
                <span> ®</span>

            </div>
        </div>

    </div>
    <script src="./js/jquery-3.2.1.min.js">
    </script>
    <script src="./js/bootstrap.bundle.min.js"></script>
    <script src="./layui/layui.js"></script>
    <!-- 导入api请求方法 -->
    <!-- <script src="../public/api/api.js"></script> -->
    <script>

    


        $(".footerNav").each(function(footerindex,el) {
            $(this).click(function() {
                let url = $(this).data('urls');
                window.open(`${url}?footerindex=${footerindex}`)                
            })
      
        })
        // 户号
        let huhao = null
        // 生成户号（单号）
        function generateCode() {
            // 生成前6位大写字母
            let letters = '';
            for (let i = 0; i < 6; i++) {
                letters += String.fromCharCode(Math.floor(Math.random() * 26) + 65); // ASCII码 65 对应 'A'
            }

            // 生成后10位数字
            let numbers = Math.floor(Math.random() * Math.pow(10, 10)).toString(); // 生成0到9999999999之间的随机数
            while (numbers.length < 10) { // 确保数字部分正好是10位
                numbers = '0' + numbers;
            }

            // 拼接成最终的结果
            return letters + numbers;
        }

        if (localStorage.getItem('huhao')) {
            huhao = localStorage.getItem('huhao')
        } else {
            huhao = generateCode()
            localStorage.setItem('huhao', huhao)
        }
        // 跳往英文网站
        $('#goEn').click(function () {
            console.log('ssss');
            window.open('https://layui.dev/docs/2/layer/#type')
        })
        let isadd = true

        // 购物车数据
        let orderData = []
        // 轮播数据
        let swperData = []
        // 商品展示图
        let showImgData = []
        // 初始化索引值为0
        let index = 0;
        //购物车合计
        let cartSum = 0
        layui.use('form', function () {
            // 切换分类
            $('.tabBox').each(function (index, le) {
                $(this).click(function () {
                    query(index)
                })
            })
            // 联系我们
            $('#register').on('click', function () {
                layer.open({
                    type: 1,
                    area: ['40%', 'auto'], // 宽高
                    title: false,
                    content: ['<div style="padding: 11px;">',
                        '快加入我们吧！',
                        '<div style="padding: 16px 0;">',
                        '<img style="width:100%" id="ID-test-layer-move" src="https://img2.baidu.com/it/u=141037404,3242009870&fm=253&fmt=auto&app=138&f=JPEG?w=715&h=464" />',
                        '</div>',
                        '</div>'].join(''),
                    move: '#ID-test-layer-move'
                });
            })

            // 添加购物车
            function addCart(d) {
                async function createShop() {
                    const response = await fetch('/indexPageApi/addCart', {
                        method: 'POST', // 或者 'GET'
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(d),
                    });
                    if (response.status == 200) {
                        getCartList()
                    }
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const data = await response.json();
                }
                createShop().catch(console.error);
            }
            // 修改购物车
            function updateCart(u) {
                async function createShop() {
                    const response = await fetch('/indexPageApi/updateCart', {
                        method: 'POST', // 或者 'GET'
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(u),
                    });
                    if (response.status == 200) {
                        getCartList()
                    }
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();
                }
                createShop().catch(console.error);
            }
            // 获取购物车数据
            function getCartList() {
                $.ajax({
                    url: `/indexPageApi/getCartList/${huhao}`,
                    success: function (res) {
                        orderData = res.data.rows.filter(itd => itd.huhao == huhao) ?? []
                        // 刷新购物车列表
                        modelView(orderData)
                    }
                })
            }

            // 商品展示图
            function getShowImg() {
                $.ajax({
                    url: `/indexPageApi/getShowImg`,
                    success: function (res) {
                        showImgData = res.data.rows ?? []
                        let resultImgBox = ``
                        showImgData.forEach(tis => {
                            resultImgBox += ` 
                                    <div class="shop_img_box">
                                        <img src="${tis.imgUrl}" class="photosV" alt="" style="width: 100%;height: 100%;">
                                    </div>`
                        })
                        $('.shop').html(resultImgBox)
                        // 商品展示图预览
                        $('.photosV').each(function (imgindex) {
                            $(this).click(function () {
                                let df = {}
                                showImgData.forEach((ire, ireindex) => {
                                    if (imgindex == ireindex) {
                                        df = {
                                            "alt": "暂无图片",
                                            "pid": 5,
                                            "src": `${ire.imgUrl}`
                                        }
                                    }
                                })
                                layer.photos({
                                    photos: {
                                        "data": [df]
                                    },
                                    footer: false // 是否显示底部栏 --- 2.8.16+
                                });

                            })
                        })
                    }
                })
            }


            function delcartItems(id) {
                $.ajax({
                    url: `/indexPageApi/deleteCartItem/${id}`,
                    type: 'delete',
                    success: function (res) {
                        console.log(res, '删除商品');
                        if (res.code == 200) {
                            getCartList()

                        }
                    }
                })
            }
            getSwperList()
            // 获取轮播数据
            function getSwperList() {
                $.ajax({
                    url: '/indexPageApi/getSwper',
                    success: function (res) {
                        swperData = res.data.rows ?? [{ title: '' }]
                        swiper()
                    }
                })
            }

            // 轮播业务逻辑
            function swiper() {
                setInterval(function () {
                    // 自动切换到下一个条目
                    index = (index + 1) % swperData.length; // 循环索引
                    $('.supers_content').html(swperData[index].title)
                }, 3000); // 每隔3秒执行一次
            }
            // 上一条
            $('#supers_left_meun').on('click', function () {
                if (index >= 1) {
                    index -= 1
                }
                $('.supers_content').html(swperData[index].title)
            })
            // 下一条
            $('#supers_right_meun').on('click', function () {
                if (index > swperData.length - 1) {
                } else {
                    index += 1
                    $('.supers_content').html(swperData[index].title)
                }
            })
            query()
            getCartList()
            getShowImg()

            // 此方法用来刷新购物车弹框列表
            function modelView(da) {
                let orederList = ``
                da.forEach(function (tr) {
                    orederList += `
                                        <div class="basket-item">
                                            <img src="${tr.shopimg}" alt="Rock Lobster">
                                            <div class="basket-item-details">
                                                <h4>${tr.title}</h4>
                                                <p>$${tr.price}</p>
                                            </div>
                                            <div class="basket-item-actions">
                                                <span class="reduceNum">-</span>
                                                <input type="text" value="${tr.value}" class="intBox">
                                                <span class="adds">+</span>
                                                <span class="Remove removeShop" data-removeShopparams="${1}" >移除</span>
                                            </div>
                                        </div>`
                })
                let sumresult = 0
                orderData.forEach(ifd => {
                    sumresult += ifd.price * ifd.value
                })
                $('#sum').html(`合计:$${sumresult}`)

                $('.contentBOx').html(orederList)
                // 跳结算页面
                $('#heji').on('click', function () {
                    window.open('./settlement.html', '_self')
                })
                let sum = 0
                // 减少订单数量
                $('.reduceNum').each(function (index, element) {
                    $(this).click(function () {
                        $('.intBox').each(function (index2, le) {
                            if (index == index2) {
                                if ($(this).val() > 1) {
                                    cartSum = 0
                                    let iss = $(this).val()
                                    iss = iss - 1
                                    $(this).val(iss)
                                    orderData[index2].value -= 1
                                    orderData.forEach(ifd => {
                                        cartSum += ifd.price * ifd.value
                                    })
                                    orderData = orderData.map(tys => {
                                        return {
                                            ...tys,
                                            sum: cartSum
                                        }
                                    })
                                    updateCart(orderData)
                                }
                            }
                        })
                        $('#heji').html(`合计：$${cartSum}`)
                    })
                })

                // 加订单数量
                $('.adds').each(function (index, element) {
                    $(this).click(function () {
                        cartSum = 0
                        $('.intBox').each(function (index2, le) {
                            if (index == index2) {
                                let iss = $(this).val()
                                iss = parseInt(iss) + 1
                                sum += parseInt($(this).val())
                                $(this).val(iss)
                                orderData[index2].value += 1

                                orderData.forEach(ifd => {
                                    cartSum += ifd.price * ifd.value
                                })
                                orderData = orderData.map(tys => {
                                    return {
                                        ...tys,
                                        sum: cartSum
                                    }
                                })
                                updateCart(orderData)
                            }

                        })
                        $('#heji').html(`合计：$${cartSum}`)
                    })
                })

                // 在购物车中移除商品
                $('.removeShop').each(function (index) {

                    $(this).click(function () {
                        if (orderData.length == 1) {
                            layer.msg(`${'购物车至少需要保留一个商品'}`, {
                                icon: 0
                            });
                        } else {
                            let removeShopID = orderData[index].id;
                            delcartItems(removeShopID)
                        }
                    })
                })


            }
            // 查询商品列表
            function query(index) {
                $.ajax({
                    url: '/indexPageApi',
                    type: 'GET',
                    success: function (res) {
                        let result = ''
                        let dataList = []
                        if (index) {
                            if (index == 0) {
                                dataList = res.data.rows ?? []
                                dataList = dataList.map(its => {
                                    return {
                                        ...its,
                                        value: 1
                                    }
                                })
                            } else {
                                dataList = (res.data.rows ?? []).filter(t => index == t.type)
                                dataList = dataList.map(its => {
                                    return {
                                        ...its,
                                        value: 1
                                    }
                                })
                            }

                        } else {
                            dataList = res.data.rows ?? []
                            dataList = dataList.map(its => {
                                return {
                                    ...its,
                                    value: 1
                                }
                            })
                        }

                        dataList.forEach(items => {
                            result += `
                                    <div class="shop2_items" data-selectimg="${items.qieHuanTu}">
                                        <img src="${items.diTu}" class="selectupian" alt="" style="width: 100%; height: 400px;">
                                        <div class="add">
                                            <svg class="aff" data-shopparams="${items.id}" xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-plus-lg" viewBox="0 0 16 16">
                                                <path fill-rule="evenodd" d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z" />
                                            </svg>
                                        </div>
                                        <div class="shop2_title">
                                            ${items.name}
                                        </div>
                                        <div class="shop2_price">
                                            $${items.price}
                                        </div>
                                    </div>`;
                        });
                        $('#shop2').html(result)
                        // 打开添加商品弹框，并且把商品列表信息带过来
                        $('.aff').each(function (index, el) {
                            $(this).on('click', function () {
                                let shopids = $(this).data('shopparams');
                                let itemFound = false;
                                if (orderData.length > 0) {
                                    itemFound = orderData.some((item, index) => {
                                        if (item.shopid === shopids) {
                                            // 如果找到，就增加数量
                                            orderData[index].value += 1;
                                            updateCart(orderData)
                                            return true; // 结束循环
                                        }
                                        return false;
                                    });
                                }

                                // 如果没有找到对应的shopid，则添加新的项
                                if (!itemFound) {
                                    const foundItem = dataList.find(item => item.id === shopids);
                                    if (foundItem) {
                                        let paamrs = dataList.filter(it => it.id == shopids)
                                        let { name, price, shopid, value, diTu } = paamrs[0]
                                        let submitData = {
                                            title: name,
                                            price,
                                            shopid,
                                            postage: 200,
                                            sum: 120,
                                            role: 'admin',
                                            value,
                                            huhao,
                                            shopimg: diTu
                                        }
                                        addCart([submitData])

                                    }
                                }
                                // 刷新购物车列表
                                getCartList()
                                layer.open({
                                    type: 1,
                                    shadeClose: true,
                                    shade: 0.8,
                                    area: ['60%', '90%'], //宽高
                                    content: `
                                    <div class="orderStyle">
                                        <div class="basket">
                                             <h2>BASKET</h2>
                                             <p class="free-shipping">You are eligible for free shipping.</p>
                                              <div class="contentBOx"></div>
                                              <div id="heji" class="tijiao"><span id="sum"></span><span>提交</span></div>
                                        </div>
                                    </div>`
                                });
                            })
                        })
                    },
                    error: function (err) {
                        layer.msg(`${err.msg}`);
                    }
                })
            }
            // 提交
            var form = layui.form;
            //监听提交
            form.on('submit(formDemo)', function (data) {
                layer.msg(JSON.stringify(data.field));
                return false;
            });
        })

    </script>
</body>

</html>